package com.asj.vivo.lock.websocket;

import static com.asj.enums.AppIdentifierDictEnums.requestTarget;
import static com.asj.enums.WebSocketStateCode.WEB_SOCKET_NORMAL_CONNECT;
import static com.asj.enums.WebSocketStateCode.WEB_SOCKET_PARAM_DEMAND_MISMATCH;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import androidx.annotation.NonNull;

import com.asj.MainActivity;
import com.asj.enums.WebSocketStateCode;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.apache.commons.lang3.StringUtils;

import java.util.Locale;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

public class LuxuryMachineWebSocketListener extends WebSocketListener {


  private final MainActivity mainActivity; // 明确类型为 MainActivity

  private WebSocket webSocket;
  //确保只有一个心跳任务在运行
  private final AtomicBoolean isPinging = new AtomicBoolean(false);
  //心跳间隔时间
  private final long pingIntervalMillis;
  //重连时间
  private final long reconnectIntervalSeconds;
  //设备标识码
  private final String IMEICode;
  //WebSocket客户端
  private final WebSocketClient webSocketClient;

  public LuxuryMachineWebSocketListener(MainActivity mainActivity,
                                        WebSocketClient webSocketClient,
                                        String IMEICode,
                                        long pingIntervalMillis,
                                        long reconnectIntervalSeconds) {
    this.mainActivity = mainActivity;
    this.webSocketClient = webSocketClient;
    this.IMEICode = IMEICode;
    this.pingIntervalMillis = pingIntervalMillis;
    this.reconnectIntervalSeconds = reconnectIntervalSeconds;
  }

  @Override
  public void onOpen(@NonNull WebSocket webSocket, @NonNull Response response) {
      this.webSocket = webSocket;
      //向后台报平安
      webSocket.send(WebSocketStateCode.getStateDescription(WEB_SOCKET_NORMAL_CONNECT));
      //发送标识码，本地ip
      WifiManager wifiManager = (WifiManager) mainActivity.getSystemService(Context.WIFI_SERVICE);
      WifiInfo wifiInfo = wifiManager.getConnectionInfo();
      int localIP = wifiInfo.getIpAddress();
      String ipAsString = String.format(Locale.US, "%d.%d.%d.%d",
              (localIP & 0xff),
              (localIP >> 8 & 0xff),
              (localIP >> 16 & 0xff),
              (localIP >> 24 & 0xff));

      JsonObject jsonObject = new JsonObject();
      jsonObject.addProperty(requestTarget.getValue(),IMEICode);
      jsonObject.addProperty("connection_local_ip",ipAsString);
      webSocket.send(jsonObject.toString());
      //开启心跳机制
      sendPingPeriodically();
  }

  /**
   * 中台可能接收到的信息范围：MDM向它请求调用SDK的指令
   * */
  @Override
  public void onMessage(@NonNull WebSocket webSocket, @NonNull String content) {
        // 接收到WebSocket消息后的处理
        System.out.println("收到了信息::"+content);
        //拦截后台发送的空内容
        if(StringUtils.isEmpty(content)){
            webSocket.send(WebSocketStateCode.getStateDescription(WEB_SOCKET_PARAM_DEMAND_MISMATCH));
        }else{
            JsonObject contentData = JsonParser.parseString(content).getAsJsonObject();
            if(contentData != null){
                //监听心跳回应
                if(contentData.get("heart") != null){
                    System.out.println("中台心跳回应！");
                    /*mainActivity.finish();
                    new OPPOControlService(mainActivity).unlockMachine();*/
                }
            }
        }
  }


  /**
   * 心跳方法
   * */
  private void sendPingPeriodically() {
    if (isPinging.compareAndSet(false, true)) {
      new Thread(() -> {
        try {
          while (isPinging.get()) {
            //每隔一段时间给服务端发送一次心跳包
            TimeUnit.SECONDS.sleep(pingIntervalMillis);
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("heart","live");
            jsonObject.addProperty(requestTarget.getValue(),IMEICode);
            //发送标识码
            webSocket.send(jsonObject.toString());
          }
        } catch (InterruptedException e) {
          Thread.currentThread().interrupt();
        } finally {
          isPinging.set(false);
        }
      }).start();
    }
  }


  /**
   * 自动重新连接方法
   * */
  private void tryReconnect() {
    new Thread(() -> {
      // 等待一段时间后重连
      try {
        TimeUnit.SECONDS.sleep(reconnectIntervalSeconds);
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        return;
      }
      //创建一个新的webSocket客户端,重新启动WebSocket连接
      webSocket = webSocketClient.initWebSocket();
    }).start();
  }



  @Override
  public void onMessage(@NonNull WebSocket webSocket, @NonNull ByteString bytes) {
    // 接收到二进制消息后的处理
    System.out.println("接收到二进制消息后的处理！");
  }

  @Override
  public void onClosing(@NonNull WebSocket webSocket, int code, @NonNull String reason) {
    //尝试重连WebSocket
    tryReconnect();
  }

  @Override
  public void onClosed(@NonNull WebSocket webSocket, int code, @NonNull String reason) {
    //尝试重连WebSocket
    tryReconnect();
  }

  @Override
  public void onFailure(@NonNull WebSocket webSocket, @NonNull Throwable t, Response response) {
    //尝试重连中
    tryReconnect();
  }
}